package com.controller.sys;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.DesUtils;
import com.common.StringUtils;
import com.common.http.HttpResult;
import com.dao.sys.SysDeptMapper;
import com.dao.sys.SysLogMapper;
import com.dao.sys.SysManageMapper;
import com.dao.sys.SysUserMapper;
import com.dao.sys.SysUserRoleMapper;
import com.model.sys.SysDept;
import com.model.sys.SysUser;
import com.model.sys.SysUserRole;
import com.service.sys.SysLogService;
import com.service.sys.SysService;
import com.service.sys.UserService;

@Controller
@RequestMapping(value = "/api")
public class UserManageController {
	static final Logger logger = LoggerFactory.getLogger(UserManageController.class);
	@Autowired
	UserService userService;
	@Autowired
	private SysManageMapper sysManageMapper;
	@Autowired
	private SysLogMapper sysLogMapper;
	@Autowired
	private SysLogService sysLogService;
	@Autowired
	private SysService sysService;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	@Autowired
	private SysDeptMapper sysDeptMapper;

	@RequestMapping(value = "sys/user/selectList", method = { RequestMethod.POST })
	@ResponseBody
	public HttpResult selectList(@RequestParam Map<String, Object> map) {
		return userService.selectList(map);
	}

	@RequestMapping(value = "/UserManage/queryItemByRoleName", method = { RequestMethod.GET })
	@ResponseBody
	public List queryItemByRoleName(@RequestParam String roleName) {
		return userService.queryItemByRoleName(roleName);
	}

	@RequestMapping(value = "/UserManage/UserListJson", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String UserListJson(HttpServletRequest request) {
		try {
			String userdept = request.getParameter("dwbm");
			String name = request.getParameter("name");
			HashMap<String, Object> hashMap = new HashMap<>();
			hashMap.put("name", name);
			hashMap.put("deptid", userdept);
			List<SysUser> list = sysUserMapper.selectAllByDw(hashMap);
			for (SysUser modelSysUser : list) {
				String pwd = DesUtils.decrypt(modelSysUser.getPwd());
				modelSysUser.setPwd(pwd);
			}
//			JSONArray jsonarray = JSONArray.fromObject(list);
			String jsonString = JSON.toJSONString(list);
//			System.out.println("UserListJson:" + jsonString);
			logger.info("UserListJson:{}", jsonString);
			// request.setAttribute("addLists", list);
			return jsonString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/UserManage/GetRoles", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String GetRoles(HttpServletRequest request) {
		try {
			String userid = request.getParameter("userid");
			List<SysUserRole> list = sysUserRoleMapper.selectAllByUserid(userid);
			String jsonString = "";
			for (SysUserRole model : list) {
				jsonString += model.getRoleid() + ",";
			}
			if (jsonString.length() > 0) {
				jsonString = jsonString.substring(0, jsonString.length() - 1);
			}
			// JSONArray jsonarray = JSONArray.fromObject(list);
			// String jsonString = jsonarray.toString();
//			System.out.println("Roles:" + jsonString);
			logger.info("Roles:{}", jsonString);
			// request.setAttribute("addLists", list);
			return jsonString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/UserManage/AddUser", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String AddUser(HttpServletRequest request) throws IOException, Exception {
		try {
			String resultString = "保存成功!";
			String czr = request.getParameter("czr");
			String userid = request.getParameter("userid");
			String password = request.getParameter("pwd");
			SysUser model = new SysUser();
			model.setUsername(request.getParameter("username"));
			model.setLoginname(request.getParameter("loginname"));
			model.setDisabled(request.getParameter("disabled"));
			model.setSuperadmin(request.getParameter("superadmin"));
			String sort = request.getParameter("sortby");
			if (sort == null || sort.equals("")) {
				sort = "0";
			}
			// 设置所在部门编码/部门名称
			String deptId = request.getParameter("userdept");
			SysDept sysDept = queryDeptCodeByDeptId(deptId);
			if (null != sysDept) {
				model.setDeptCode(sysDept.getDwbm());
				model.setDeptName(sysDept.getDwmc());
			}

			model.setUsersort(Short.parseShort(sort));
			model.setDeptid(request.getParameter("userdept"));
			model.setOaDeptId(request.getParameter("oaDeptId"));
			model.setOaDeptName(request.getParameter("oaDeptName"));
			model.setPhone(request.getParameter("phone"));
			model.setTel(request.getParameter("tel"));
			model.setMail(request.getParameter("mail"));
			model.setPwd(DesUtils.encrypt(password));
			model.setWxid(request.getParameter("wxid"));
			model.setCasid(request.getParameter("casid"));
			model.setSap(request.getParameter("sap"));
			model.setHlevel(request.getParameter("hlevel"));
			model.setDatapermission(request.getParameter("datapermission"));
			model.setBtnPermission(request.getParameter("btnPermission"));
			if (StringUtils.isNotNull(request.getParameter("oa"))) {
				model.setOa(Integer.parseInt(request.getParameter("oa")));
			}
			String roles = request.getParameter("roles");

			if (userid == null || userid.equals("")) {
				if (sysUserMapper.existLoginame(model.getLoginname()) > 0) {
					resultString = "登录名已存在!";
					return resultString;
				}
				userid = UUID.randomUUID().toString();
				model.setUserid(userid);
				resultString = sysService.addUser(model, roles) > 0 ? "保存成功!" : "保存失败!";

			} else {
				if (sysUserMapper.existByLoginameUserid(model.getLoginname(), userid) > 0) {
					resultString = "!";
					return resultString;
				}
				model.setUserid(userid);
				resultString = sysService.updateUser(model, roles) > 0 ? "保存成功!" : "保存失败!";
			}
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/UserManage/DelUser", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String DelUser(HttpServletRequest request) {
		try {
			String userid = request.getParameter("userid");
			String czr = request.getParameter("czr");
			String resultString = sysService.deleteUser(userid) > 0 ? "保存成功!" : "保存失败!";
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/UserManage/ChangePWD", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String ChangePWD(HttpServletRequest request) {
		try {
			String resultString = "保存成功!";
			String userid = request.getParameter("loginname");
			String czr = request.getParameter("userid");
			String pwd = request.getParameter("pwd1");
			SysUser model = sysUserMapper.selectByNamePwd(userid, DesUtils.encrypt(pwd));
			if (model == null) {
				resultString = "密码不正确!";
				return resultString;
			}
			String pwd2 = request.getParameter("pwd2");
			String pwd3 = request.getParameter("pwd3");
			if (!pwd2.equals(pwd3)) {
				resultString = "密码不一致!";
				return resultString;
			}
			model.setPwd(DesUtils.encrypt(pwd2));
			resultString = sysUserMapper.updateByPrimaryKey(model) > 0 ? "保存成功!" : "保存失败!";
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	/**
	 * deptId 根据部门id获取机构编码
	 *
	 * @param deptId
	 * @return
	 */
	private SysDept queryDeptCodeByDeptId(String deptId) {
		SysDept sysDept = sysDeptMapper.selectByPrimaryKey(deptId);
		return sysDept;
	}
}
